package org.lsy.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.lsy.service.CodeService;
import org.lsy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author liusy95
 * @version 1.0
 * @date 2020/7/29
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Reference
    private CodeService codeService;

    private static final String DEFAULT_COOKIE = "token";

    @GetMapping("/register/{email}/{password}/{code}")
    public Boolean register(@PathVariable String email,
                            @PathVariable String password,
                            @PathVariable String code,
                            HttpServletResponse response) {
        //首先判断验证码
        Integer validate = codeService.validateCode(email, code);
        if (validate == 0) {
            try {
                userService.register(email, password, response);
                return true;
            } catch (Exception e) {
                log.error("保存账户失败，账户：{}，原因：{}", email, e.toString());
            }
        }
        return false;
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable String email,
                        @PathVariable String password,
                        HttpServletResponse response) {
        return userService.login(email, password, response);
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {
        return userService.info(token);
    }

    @GetMapping("/info")
    public String info(HttpServletRequest request) {
        String token = Arrays.stream(request.getCookies())
                .filter(cookie -> DEFAULT_COOKIE.equals(cookie.getName()))
                .map(Cookie::getValue)
                .findAny()
                .orElse("");
        return userService.info(token);
    }
}
